<template>
  <div class="rule-list-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span>功能节点</span>
            <el-button
              class="refresh-button"
              @click="handleRefresh"
              :icon="Refresh"
              circle
            ></el-button>
          </div>
          <div class="header-right">
            <el-input
              v-model="searchKeywords"
              placeholder="搜索节点名称、URL地址"
              style="width: 300px; margin-right: 10px"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button @click="handleSearch">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
            <el-button class="add-button" @click="handleAdd">添加根节点</el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="ruleList"
        style="width: 100%"
        row-key="id"
        border
        lazy
        :load="loadChildNodes"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :row-class-name="tableRowClassName"
        :cell-class-name="tableCellClassName"
        :default-expand-all="false"
      >
        <el-table-column prop="id" label="ID" width="80" type="index" />
        <el-table-column prop="title" label="节点名称" min-width="200">
          <template #default="{ row }">
            <div class="level-indicator-wrapper">
              <div :class="['level-indicator', `level-indicator-${row._level || 0}`]"></div>
              <div :class="['title-content', getTitleClass(row)]">
                <span
                  v-if="row.icon"
                  :class="`el-icon-${row.icon}`"
                  style="margin-right: 8px"
                ></span>
                {{ row.title }}
                <span v-if="row.menu === 1" class="menu-badge">[菜单]</span>
                <span :class="getLevelLabelClass(row)">{{ getLevelLabel(row) }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="pid" label="父ID" width="100" />
        <el-table-column prop="module" label="所属模块" width="120" />
        <el-table-column prop="src" label="URL地址" min-width="150" show-overflow-tooltip />
        <el-table-column prop="name" label="操作名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="menu" label="是否菜单" width="100">
          <template #default="{ row }">
            <span v-if="row.menu === 1" class="green">是</span>
            <span v-else class="red">否</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag v-if="row.status === 1" type="success">正常</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button class="view-button" link size="small" @click="handleView(row)">
              查看
            </el-button>
            <el-button class="add-child-button" link size="small" @click="handleAddChild(row)">
              添加子节点
            </el-button>
            <el-button class="edit-button" link size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button class="delete-button" link size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑规则抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      :title="drawerTitle"
      size="500px"
      direction="rtl"
      @close="handleDrawerClose"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="ruleRules"
        label-width="100px"
        style="padding: 20px 0"
      >
        <el-form-item label="父级菜单/节点" prop="pid">
          <el-select
            v-model="ruleForm.pid"
            placeholder="请选择父级菜单/节点"
            @change="handleParentChange"
            filterable
          >
            <el-option value="0" label="作为顶级菜单/节点" />
            <el-option
              v-for="item in parentOptions"
              :key="item.id"
              :label="item.titleWithLevel"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属模块" prop="module">
          <el-select v-model="ruleForm.module" placeholder="请选择模块" filterable>
            <el-option
              v-for="item in moduleOptions"
              :key="item.name"
              :label="item.title"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="节点名称" prop="title">
          <el-input v-model="ruleForm.title" placeholder="请输入节点名称" />
        </el-form-item>
        <el-form-item label="操作名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入操作名称" />
        </el-form-item>
        <el-form-item label="URL地址">
          <el-input v-model="ruleForm.src" placeholder="请输入URL地址" />
        </el-form-item>
        <el-form-item label="菜单图标">
          <el-input v-model="ruleForm.icon" placeholder="请输入图标类名(例如: menu)" />
        </el-form-item>
        <el-form-item label="是否菜单">
          <el-switch v-model="ruleForm.menu" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="左侧菜单显示">
          <el-radio-group v-model="ruleForm.showLeftMenu">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">不是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="ruleForm.sort" :min="0" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="ruleForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div class="drawer-footer">
        <el-button @click="drawerVisible = false">取消</el-button>
        <el-button class="submit-button" @click="submitRule">确定</el-button>
      </div>
    </el-drawer>

    <!-- 查看规则详情抽屉 -->
    <el-drawer v-model="viewDrawerVisible" title="查看规则详情" size="400px" direction="rtl">
      <div v-if="currentViewRow" class="view-detail-container">
        <div class="detail-item">
          <span class="detail-label">ID号:</span>
          <span class="detail-value">{{ currentViewRow.id }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">菜单/节点名称:</span>
          <span class="detail-value">{{ currentViewRow.title }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">父ID:</span>
          <span class="detail-value">{{ currentViewRow.pid }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">URL链接:</span>
          <span class="detail-value">{{ currentViewRow.src || '无' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">是否是菜单:</span>
          <span class="detail-value">{{ currentViewRow.menu === 1 ? '是' : '否' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">操作日志名称:</span>
          <span class="detail-value">{{ currentViewRow.name || '无' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">排序:</span>
          <span class="detail-value">{{ currentViewRow.sort }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">菜单图标:</span>
          <span class="detail-value">{{ currentViewRow.icon || '无' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">创建时间:</span>
          <span class="detail-value">{{ currentViewRow.create_time_format || '无' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">更新时间:</span>
          <span class="detail-value">{{ currentViewRow.update_time_format || '无' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">子节点数量:</span>
          <span class="detail-value">{{ currentViewRow.children_count || 0 }}</span>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
  import { Refresh, Search } from '@element-plus/icons-vue'
  import { getRuleList, saveRule, deleteRule, clearRuleCache } from '@/api/home/rule'

  // 类型定义
  interface RuleItem {
    id: number
    pid: number
    module: string
    title: string
    name: string
    src: string
    status: number
    condition: string
    listorder: number
    desc: string
    sort: number
    menu: number
    icon: string
    children?: RuleItem[]
    hasChildren?: boolean
    _level?: number
    [key: string]: any
  }

  // 数据相关
  const ruleList = ref<RuleItem[]>([])
  const loading = ref(false)
  const nodeLoadingMap = ref<{ [key: number]: boolean }>({})
  const searchKeywords = ref('')

  // 抽屉相关
  const drawerVisible = ref(false)
  const viewDrawerVisible = ref(false)
  const drawerTitle = ref('')
  const isEdit = ref(false)
  const currentViewRow = ref<any>(null)

  // 表单数据
  const ruleForm = reactive({
    id: 0,
    pid: 0,
    module: '',
    title: '',
    name: '',
    src: '',
    status: 1,
    condition: '',
    listorder: 0,
    desc: '',
    sort: 0,
    menu: 1,
    icon: '',
    showLeftMenu: 1, // 左侧菜单显示，默认为显示
  })

  // 表单验证规则
  const ruleRules = {
    title: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
    name: [{ required: true, message: '请输入权限标识', trigger: 'blur' }],
  }

  // 表单引用
  const ruleFormRef = ref()

  // 所有节点选项数据
  const parentOptions = ref<{ id: number; titleWithLevel: string }[]>([])

  // 模块选项数据
  const moduleOptions = ref<{ name: string; title: string }[]>([])

  // 获取所有节点数据用于下拉选择
  const loadAllNodesForDropdown = async () => {
    try {
      console.log('开始加载所有节点数据用于下拉选择')
      const response: any = await getRuleList({
        tree: true,
        withLevel: true,
        pid: 0, // 获取所有层级的节点
      })

      if (response && response.data && Array.isArray(response.data)) {
        parentOptions.value = []
        // 递归处理树结构，将所有节点添加到选项中
        const processNode = (nodes: any[], level: number = 0) => {
          nodes.forEach(node => {
            // 构建带层级的标题
            const indent = level > 0 ? '|--'.repeat(level) + ' ' : ''
            parentOptions.value.push({
              id: node.id,
              titleWithLevel: `${indent}${node.title}`,
            })

            // 递归处理子节点
            if (node.children && Array.isArray(node.children) && node.children.length > 0) {
              processNode(node.children, level + 1)
            }
          })
        }

        processNode(response.data)
        console.log('加载所有节点数据完成，总数量:', parentOptions.value.length)
      } else {
        console.warn('API返回数据格式不正确或为空')
        parentOptions.value = []
      }
    } catch (error) {
      console.error('加载所有节点数据失败:', error)
      ElMessage.error('加载节点数据失败')
      parentOptions.value = []
    }
  }

  // 加载模块配置列表用于下拉选择
  const loadModuleOptions = async () => {
    try {
      console.log('开始加载模块配置列表')
      // 从API获取模块配置列表
      const response: any = await getRuleList({
        module: true, // 只获取模块列表
      })

      if (response && response.data && Array.isArray(response.data)) {
        moduleOptions.value = response.data.map((module: any) => ({
          name: module.name,
          title: module.title,
        }))
        console.log('加载模块配置列表完成，总数量:', moduleOptions.value.length)
      } else {
        // 如果API返回为空，使用默认模块数据作为后备
        moduleOptions.value = [
          { name: 'home', title: '系统设置' },
          { name: 'user', title: '用户管理' },
          { name: 'oa', title: '办公管理' },
        ]
        console.warn('API返回模块数据为空，使用默认模块数据')
      }
    } catch (error) {
      console.error('加载模块配置列表失败:', error)
      // 出错时使用默认模块数据
      moduleOptions.value = [
        { name: 'home', title: '系统设置' },
        { name: 'user', title: '用户管理' },
        { name: 'oa', title: '办公管理' },
      ]
      ElMessage.warning('加载模块数据失败，使用默认模块列表')
    }
  }

  // 获取根节点数据
  const getRootNodes = async (keywords: string = '') => {
    try {
      loading.value = true
      const response: any = await getRuleList({
        tree: true,
        withLevel: true,
        pid: 0, // 只获取顶级节点及子节点
        keywords: keywords, // 添加搜索关键词
      })

      if (response && response.data && Array.isArray(response.data)) {
        // 处理树结构数据，确保层级信息正确设置
        ruleList.value = response.data.map((node: any) => {
          // 详细记录hasChildren属性的判断逻辑
          let hasChildrenValue = false
          const hasBackendHasChildren = node.hasChildren !== undefined
          const hasChildrenData = !!node.children && node.children.length > 0

          if (hasBackendHasChildren) {
            hasChildrenValue = node.hasChildren
            console.log(
              `根节点 ${node.id} (${node.title}) 使用后端返回的hasChildren: ${hasChildrenValue}`
            )
          } else {
            hasChildrenValue = hasChildrenData
            console.log(
              `根节点 ${node.id} (${node.title}) 根据children数组设置hasChildren: ${hasChildrenValue}`
            )
          }

          // 对于根节点，层级应该是0
          const nodeLevel = 0

          return {
            ...node,
            _level: nodeLevel,
            hasChildren: hasChildrenValue,
            // 确保Element Plus能够正确识别和显示展开图标
            'has-children': hasChildrenValue,
          }
        })
      } else {
        ruleList.value = []
      }
    } catch (error) {
      console.error('获取根节点数据失败:', error)
      ElMessage.error('获取节点数据失败')
      ruleList.value = []
    } finally {
      loading.value = false
    }
  }

  // 懒加载子节点
  const loadChildNodes = async (row: any, treeNode: any, resolve: any) => {
    console.log('开始加载子节点:', row)

    // 验证必要参数是否存在
    if (!resolve) {
      console.error('加载子节点失败: 缺少resolve函数')
      return
    }

    // 获取父节点ID
    const parentId = row?.id

    console.log('父节点ID:', parentId, '加载状态:', nodeLoadingMap.value[parentId])

    // 避免重复加载和无效父节点
    if (!parentId) {
      console.error('加载子节点失败: 无效的父节点ID')
      resolve([])
      return
    }

    // 防止重复加载
    if (nodeLoadingMap.value[parentId]) {
      console.warn('子节点已在加载中，避免重复请求')
      resolve([])
      return
    }

    // 设置加载状态
    nodeLoadingMap.value[parentId] = true

    // 存储超时定时器的引用，以便在成功加载后清除
    let timeoutTimer: number | null = null

    try {
      // 优先检查是否已有子节点数据
      if (row && row.children && Array.isArray(row.children) && row.children.length > 0) {
        console.log('使用已有的子节点数据，数量:', row.children.length)

        // 处理已有的子节点数据，确保正确设置hasChildren属性和层级
        const parentLevel = row._level || 0
        const processedChildren = row.children.map((node: any) => ({
          ...node,
          _level: parentLevel + 1, // 确保层级正确计算：父节点的_level + 1
          // 确保正确设置hasChildren属性，优先使用后端返回值，否则检查children数组
          hasChildren:
            node.hasChildren !== undefined
              ? node.hasChildren
              : !!node.children && node.children.length > 0,
          // 确保Element Plus能够正确识别和显示展开图标
          'has-children':
            node.hasChildren !== undefined
              ? node.hasChildren
              : !!node.children && node.children.length > 0,
        }))

        // 延迟一下，让动画更平滑
        setTimeout(() => {
          resolve(processedChildren)
          nodeLoadingMap.value[parentId] = false
          console.log('使用已有数据完成加载子节点')
        }, 100)
        return
      }

      // 设置超时处理，确保加载状态不会一直卡住
      const timeoutPromise = new Promise((_, reject) => {
        timeoutTimer = setTimeout(() => {
          reject(new Error('加载子节点超时'))
        }, 10000) as unknown as number // 10秒超时
      })

      console.log('请求API获取子节点数据，父ID:', parentId)

      // 使用Promise.race实现超时控制
      const response: any = await Promise.race([
        getRuleList({
          tree: true,
          withLevel: true,
          pid: parentId,
        }),
        timeoutPromise,
      ])

      console.log('API返回结果:', response)

      let childNodes: any[] = []

      if (response && response.data && Array.isArray(response.data)) {
        console.log('API返回子节点数量:', response.data.length)
        // 处理子节点数据，确保层级正确计算
        const parentLevel = row._level || 0
        childNodes = response.data.map((node: any) => {
          // 详细记录hasChildren属性的判断逻辑
          let hasChildrenValue = false
          const hasBackendHasChildren = node.hasChildren !== undefined
          const hasChildrenData = !!node.children && node.children.length > 0

          // 总是设置hasChildren属性，确保所有层级的节点都能正确显示展开按钮
          if (hasBackendHasChildren) {
            hasChildrenValue = node.hasChildren
            console.log(
              `节点 ${node.id} (${node.title}) 使用后端返回的hasChildren: ${hasChildrenValue}`
            )
          } else {
            hasChildrenValue = hasChildrenData
            console.log(
              `节点 ${node.id} (${node.title}) 根据children数组设置hasChildren: ${hasChildrenValue} (children数量: ${node.children ? node.children.length : 0})`
            )
          }

          // 确保层级属性正确计算：父节点的_level + 1
          const childLevel = parentLevel + 1

          console.log(
            `节点 ${node.id} (${node.title}) - 父节点层级: ${parentLevel}, 子节点层级: ${childLevel}`
          )

          return {
            ...node,
            _level: childLevel,
            hasChildren: hasChildrenValue,
            // 确保Element Plus能够正确识别和显示展开图标
            'has-children': hasChildrenValue,
          }
        })

        // 打印处理后的子节点数据，特别是hasChildren属性
        console.log('处理后的子节点数据:', childNodes)
        // 特别检查第三级及以上节点的hasChildren属性
        const deepNodes = childNodes.filter(node => node._level >= 2)
        if (deepNodes.length > 0) {
          console.log(
            '第三级及以上节点详情:',
            deepNodes.map(node => ({
              id: node.id,
              title: node.title,
              _level: node._level,
              hasChildren: node.hasChildren,
              childrenCount: node.children ? node.children.length : 0,
            }))
          )
        }
      } else {
        console.warn('API返回数据格式不正确或为空')
      }

      // 延迟一下，让动画更平滑
      setTimeout(() => {
        console.log('解析子节点数据，数量:', childNodes.length)
        resolve(childNodes)
        nodeLoadingMap.value[parentId] = false
        console.log('子节点加载完成')
      }, 200)
    } catch (error) {
      console.error('加载子节点失败:', error)
      ElMessage.error('加载子节点失败: ' + (error as Error).message)
      resolve([])
      nodeLoadingMap.value[parentId] = false
    } finally {
      // 清除超时定时器
      if (timeoutTimer !== null) {
        clearTimeout(timeoutTimer)
      }
    }
  }

  // 处理父级变更
  const handleParentChange = (value: any) => {
    ruleForm.pid = value
  }

  // 查看规则详情
  const handleView = (row: any) => {
    currentViewRow.value = row
    viewDrawerVisible.value = true
  }

  // 添加子菜单
  const handleAddChild = async (row: any) => {
    isEdit.value = false
    drawerTitle.value = '添加子菜单/节点'
    ruleForm.id = 0
    ruleForm.pid = row.id

    // 确保module字段使用的是名称而不是标题
    let moduleName = row.module || ''
    if (moduleName && moduleOptions.value.length > 0) {
      const matchedModule = moduleOptions.value.find(item => item.title === moduleName)
      if (matchedModule) {
        moduleName = matchedModule.name
      }
    } else {
      // 先加载模块数据，再设置module值
      await loadModuleOptions()
      if (row.module) {
        const matchedModule = moduleOptions.value.find(item => item.title === row.module)
        if (matchedModule) {
          moduleName = matchedModule.name
        }
      }
    }

    ruleForm.module = moduleName
    ruleForm.title = ''
    ruleForm.name = ''
    ruleForm.src = ''
    ruleForm.status = 1
    ruleForm.condition = ''
    ruleForm.listorder = 0
    ruleForm.desc = ''
    ruleForm.sort = 0
    ruleForm.menu = 1
    ruleForm.icon = ''
    ruleForm.showLeftMenu = 1

    // 加载所有节点数据用于下拉选择
    await Promise.all([loadAllNodesForDropdown()])

    drawerVisible.value = true
  }

  // 处理添加
  const handleAdd = async (row: any = {}) => {
    isEdit.value = false
    drawerTitle.value = '添加根节点'
    ruleForm.id = 0
    ruleForm.pid = row.id || 0
    ruleForm.module = ''
    ruleForm.title = ''
    ruleForm.name = ''
    ruleForm.src = ''
    ruleForm.status = 1
    ruleForm.condition = ''
    ruleForm.listorder = 0
    ruleForm.desc = ''
    ruleForm.sort = 0
    ruleForm.menu = 1
    ruleForm.icon = ''
    ruleForm.showLeftMenu = 1

    // 加载所有节点数据用于下拉选择
    await Promise.all([loadAllNodesForDropdown(), loadModuleOptions()])

    drawerVisible.value = true
  }

  // 处理编辑
  const handleEdit = async (row: any) => {
    isEdit.value = true
    drawerTitle.value = '编辑节点'
    ruleForm.id = row.id
    ruleForm.pid = row.pid
    // 确保module字段使用的是名称而不是标题
    // 检查row.module是否与moduleOptions中的某个title匹配，如果是，则使用对应的name
    let moduleName = row.module || ''
    if (moduleName && moduleOptions.value.length > 0) {
      const matchedModule = moduleOptions.value.find(item => item.title === moduleName)
      if (matchedModule) {
        moduleName = matchedModule.name
      }
    }
    ruleForm.module = moduleName
    ruleForm.title = row.title
    ruleForm.name = row.name
    ruleForm.src = row.src
    ruleForm.status = row.status
    ruleForm.condition = row.condition
    ruleForm.listorder = row.listorder
    ruleForm.desc = row.desc
    ruleForm.sort = row.sort || 0
    ruleForm.menu = row.menu || 1
    ruleForm.icon = row.icon || ''
    ruleForm.showLeftMenu = row.showLeftMenu !== undefined ? row.showLeftMenu : 1

    // 加载所有节点数据用于下拉选择
    await Promise.all([loadAllNodesForDropdown(), loadModuleOptions()])

    drawerVisible.value = true
  }

  // 删除规则
  const handleDelete = async (row: any) => {
    ElMessageBox.confirm(`确认删除节点【${row.title}】吗？`, '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          const loadingInstance = ElLoading.service({ text: '删除中...' })

          const response: any = await deleteRule({ id: row.id })

          ElMessage.success('删除成功')

          // 只刷新当前层级数据，不重新加载整个列表
          if (row.pid === 0) {
            // 如果是根节点，重新加载根节点列表
            await getRootNodes(searchKeywords.value)
          } else {
            // 如果是子节点，找到父节点并刷新其子节点
            // 这里可以通过key来强制更新对应的行
            const parentNode = ruleList.value.find(item => item.id === row.pid)
            if (parentNode) {
              parentNode.hasChildren = true // 强制标记为有子节点，以便重新加载
            }

            // 简单的处理方式：重新加载整个列表
            await getRootNodes(searchKeywords.value)
          }
        } catch (error) {
          ElMessage.error('删除失败')
        } finally {
          ElLoading.service().close()
        }
      })
      .catch(() => {
        // 用户取消删除
      })
  }

  // 提交规则
  const submitRule = async () => {
    if (!ruleFormRef.value) return

    try {
      // 在提交前确保module字段使用的是name而不是title
      let moduleName = ruleForm.module
      if (moduleName && moduleOptions.value.length > 0) {
        // 检查是否是title值
        const matchedModule = moduleOptions.value.find(item => item.title === moduleName)
        if (matchedModule) {
          moduleName = matchedModule.name
          console.log('修复模块值：从title', moduleName, '替换为name', matchedModule.name)
        }
      }

      await ruleFormRef.value.validate()

      const params = {
        id: ruleForm.id,
        pid: ruleForm.pid,
        module: moduleName,
        title: ruleForm.title,
        name: ruleForm.name,
        src: ruleForm.src,
        status: ruleForm.status,
        condition: ruleForm.condition,
        listorder: ruleForm.listorder,
        desc: ruleForm.desc,
        sort: ruleForm.sort,
        menu: ruleForm.menu,
        icon: ruleForm.icon,
        showLeftMenu: ruleForm.showLeftMenu,
      }

      console.log('提交的参数：', params)

      const loadingInstance = ElLoading.service({ text: '保存中...' })

      await saveRule(params)

      ElMessage.success(isEdit.value ? '编辑成功' : '添加成功')
      drawerVisible.value = false

      // 只刷新受影响的部分
      if (ruleForm.pid === 0 || (isEdit.value && ruleForm.pid === 0)) {
        // 如果是根节点相关操作，重新加载根节点
        await getRootNodes(searchKeywords.value)
      } else {
        // 其他情况，找到父节点并重新加载
        const parentNode = ruleList.value.find(item => item.id === ruleForm.pid)
        if (parentNode) {
          parentNode.hasChildren = true
        }
        await getRootNodes(searchKeywords.value)
      }
    } catch (error) {
      ElMessage.error(isEdit.value ? '编辑失败' : '添加失败')
    } finally {
      ElLoading.service().close()
    }
  }

  // 关闭抽屉
  const handleDrawerClose = () => {
    ruleFormRef.value?.resetFields()
  }

  // 刷新数据
  const handleRefresh = async () => {
    try {
      // 清除后端缓存
      await clearRuleCache()
      ElMessage.success('缓存清除成功')

      // 重新加载数据
      await getRootNodes(searchKeywords.value)
      ElMessage.success('数据刷新成功')
    } catch (error) {
      ElMessage.error('刷新失败')
    }
  }

  // 搜索处理
  const handleSearch = () => {
    getRootNodes(searchKeywords.value)
  }

  // 组件挂载时获取数据
  onMounted(() => {
    getRootNodes()
  })

  // 添加行样式类名方法
  const tableRowClassName = ({ row }: { row: any }) => {
    if (!row) return ''

    const level = row._level !== undefined ? row._level : 0
    return `level-${level}-row`
  }

  // 添加单元格样式类名方法
  const tableCellClassName = ({ row, column }: { row: any; column: any }) => {
    if (!row || column.property !== 'title') return ''

    const level = row._level !== undefined ? row._level : 0
    return `level-${level}-cell`
  }

  // 获取标题样式类
  const getTitleClass = (row: any) => {
    if (!row) return 'level-0-title'

    const level = row._level !== undefined ? row._level : 0
    return `level-${level}-title`
  }

  // 获取层级标签
  const getLevelLabel = (row: any) => {
    if (!row) return '[未知]'

    const level = row._level !== undefined ? row._level : 0
    switch (level) {
      case 0:
        return '[顶级]'
      case 1:
        return '[二级]'
      case 2:
        return '[三级]'
      default:
        return `[${level + 1}级]`
    }
  }

  // 获取层级标签的样式类
  const getLevelLabelClass = (row: any) => {
    if (!row) return 'level-0-label'

    const level = row._level !== undefined ? row._level : 0
    return `level-${level}-label`
  }
</script>

<style scoped>
  .rule-list-container {
    padding: 20px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .header-left {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .header-right {
    display: flex;
    align-items: center;
  }

  .refresh-button {
    background-color: #409eff;
    border-color: #409eff;
    color: white;
  }

  .refresh-button:hover {
    background-color: #66b1ff;
    border-color: #66b1ff;
    color: white;
  }

  .red {
    color: #f56c6c;
  }

  .green {
    color: #67c23a;
  }

  /* 层级指示器容器 */
  .level-indicator-wrapper {
    display: flex;
    align-items: center;
    min-height: 36px;
  }

  /* 层级竖线指示器 */
  .level-indicator {
    width: 3px;
    height: 20px;
    margin-right: 8px;
    border-radius: 2px;
    flex-shrink: 0;
  }

  .level-indicator-0 {
    background-color: #409eff;
    height: 24px;
  }

  .level-indicator-1 {
    background-color: #67c23a;
    margin-left: 20px;
  }

  .level-indicator-2 {
    background-color: #e6a23c;
    margin-left: 40px;
  }

  .level-indicator-3 {
    background-color: #f56c6c;
    margin-left: 60px;
  }

  .level-indicator-4,
  .level-indicator-5,
  .level-indicator-6 {
    background-color: #909399;
    margin-left: calc(20px * (4 - 1));
  }

  /* 标题内容容器 */
  .title-content {
    display: flex;
    align-items: center;
    padding: 4px 0;
  }

  /* 菜单徽章 */
  .menu-badge {
    font-size: 11px;
    color: #409eff;
    background-color: #ecf5ff;
    padding: 2px 6px;
    border-radius: 2px;
    margin-left: 6px;
  }

  /* 行样式 - 增强权重，确保样式生效 */
  :deep(.el-table__body .level-0-row) {
    background-color: #f0f7ff !important;
    font-weight: bold !important;
  }
  :deep(.el-table__body .level-0-row .level-0-cell) {
    border-left: 4px solid #409eff !important;
    padding-left: 24px !important;
  }

  /* 第一级节点 */
  :deep(.el-table__body .level-1-row) {
    background-color: #f6fbff !important;
  }
  :deep(.el-table__body .level-1-row .level-1-cell) {
    border-left: 4px solid #67c23a !important;
    padding-left: 24px !important;
  }

  /* 第二级节点 */
  :deep(.el-table__body .level-2-row) {
    background-color: #fafdff !important;
  }
  :deep(.el-table__body .level-2-row .level-2-cell) {
    border-left: 4px solid #e6a23c !important;
    padding-left: 24px !important;
  }

  /* 第三级节点 */
  :deep(.el-table__body .level-3-row) {
    background-color: #fff9f9 !important;
  }
  :deep(.el-table__body .level-3-row .level-3-cell) {
    border-left: 4px solid #f56c6c !important;
    padding-left: 24px !important;
  }

  /* 第四级及以下节点 */
  :deep(.el-table__body .level-4-row),
  :deep(.el-table__body .level-5-row),
  :deep(.el-table__body .level-6-row) {
    background-color: #fafafa !important;
  }
  :deep(.el-table__body .level-4-row .level-4-cell),
  :deep(.el-table__body .level-5-row .level-5-cell),
  :deep(.el-table__body .level-6-row .level-6-cell) {
    border-left: 4px solid #909399 !important;
    padding-left: 24px !important;
  }

  /* 标题文字样式增强 - 增强权重 */
  :deep(.el-table__body .level-0-title) {
    color: #1890ff !important;
    font-weight: bold !important;
    font-size: 16px !important;
    padding-left: 0px !important;
  }

  :deep(.el-table__body .level-1-title) {
    color: #52c41a !important;
    font-size: 15px !important;
    font-weight: 600 !important;
    padding-left: 15px !important;
  }

  :deep(.el-table__body .level-2-title) {
    color: #fa8c16 !important;
    font-size: 14px !important;
    font-weight: 500 !important;
    padding-left: 30px !important;
  }

  :deep(.el-table__body .level-3-title) {
    color: #f5222d !important;
    font-size: 14px !important;
    padding-left: 45px !important;
  }

  :deep(.el-table__body .level-4-title),
  :deep(.el-table__body .level-5-title),
  :deep(.el-table__body .level-6-title) {
    color: #722ed1 !important;
    font-size: 13px !important;
    padding-left: 60px !important;
  }

  /* 增强行悬停效果 */
  :deep(.el-table__row:hover td) {
    background-color: #ebf5ff !important;
  }

  /* 树形表格的展开图标样式优化 - 增强权重 */
  :deep(.el-table__body .el-table__expand-icon) {
    margin-right: 4px !important;
    font-size: 16px !important;
    display: inline-flex !important;
    align-items: center !important;
    justify-content: center !important;
    width: 20px !important;
    height: 20px !important;
  }

  :deep(.el-table__body .el-table__expand-icon .el-icon) {
    font-size: 16px !important;
    transition: transform 0.2s ease !important;
    color: #666 !important;
  }

  :deep(.el-table__body .el-table__expand-icon--expanded .el-icon) {
    transform: rotate(90deg) !important;
  }

  /* 确保有子节点的行总是显示展开图标 */
  :deep(.el-table__body .el-table__row.has-children .el-table__expand-icon) {
    display: inline-flex !important;
    visibility: visible !important;
    opacity: 1 !important;
  }

  /* 层级标签样式 - 增强权重 */
  :deep(.el-table__body .level-0-label) {
    font-size: 11px !important;
    color: #409eff !important;
    background-color: #ecf5ff !important;
    padding: 1px 5px !important;
    border-radius: 2px !important;
    margin-left: 8px !important;
  }

  :deep(.el-table__body .level-1-label) {
    font-size: 11px !important;
    color: #67c23a !important;
    background-color: #f0f9eb !important;
    padding: 1px 5px !important;
    border-radius: 2px !important;
    margin-left: 8px !important;
  }

  :deep(.el-table__body .level-2-label) {
    font-size: 11px !important;
    color: #e6a23c !important;
    background-color: #fdf6ec !important;
    padding: 1px 5px !important;
    border-radius: 2px !important;
    margin-left: 8px !important;
  }

  :deep(.el-table__body .level-3-label) {
    font-size: 11px !important;
    color: #f56c6c !important;
    background-color: #fef0f0 !important;
    padding: 1px 5px !important;
    border-radius: 2px !important;
    margin-left: 8px !important;
  }

  :deep(.el-table__body .level-4-label),
  :deep(.el-table__body .level-5-label),
  :deep(.el-table__body .level-6-label) {
    font-size: 11px !important;
    color: #909399;
    background-color: #f4f4f5;
    padding: 1px 5px;
    border-radius: 2px;
    margin-left: 8px;
  }

  /* 添加按钮样式 */
  .add-button {
    background-color: #67c23a;
    border-color: #67c23a;
    color: white;
  }

  .add-button:hover {
    background-color: #5dad34;
    border-color: #5dad34;
    color: white;
  }

  /* 查看按钮样式 */
  .view-button {
    color: #409eff;
  }

  .view-button:hover {
    color: #66b1ff;
  }

  /* 添加子节点按钮样式 */
  .add-child-button {
    color: #67c23a;
  }

  .add-child-button:hover {
    color: #85ce61;
  }

  /* 编辑按钮样式 */
  .edit-button {
    color: #e6a23c;
  }

  .edit-button:hover {
    color: #ebb563;
  }

  /* 删除按钮样式 */
  .delete-button {
    color: #f56c6c;
  }

  .delete-button:hover {
    color: #f78989;
  }

  /* 抽屉样式 */
  .drawer-footer {
    display: flex;
    justify-content: flex-end;
    padding: 20px;
    border-top: 1px solid #f0f0f0;
    margin-top: 20px;
  }

  .drawer-footer .el-button {
    margin-left: 10px;
  }

  /* 提交按钮样式 */
  .submit-button {
    background-color: #67c23a;
    border-color: #67c23a;
    color: white;
  }

  .submit-button:hover {
    background-color: #5dad34;
    border-color: #5dad34;
    color: white;
  }

  /* 查看详情样式 */
  .view-detail-container {
    padding: 20px;
  }

  .detail-item {
    display: flex;
    margin-bottom: 16px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;
  }

  .detail-item:last-child {
    border-bottom: none;
    margin-bottom: 0;
    padding-bottom: 0;
  }

  .detail-label {
    width: 120px;
    color: #909399;
    font-weight: 500;
  }

  .detail-value {
    flex: 1;
    color: #303133;
  }

  /* 优化表格行高和间距 */
  :deep(.el-table__row) {
    transition: all 0.2s ease;
  }

  :deep(.el-table__body td) {
    padding: 10px 12px;
  }
</style>
